package com.mnotice.message.config.loader;

import com.mnotice.common.entity.message.FreemarkerTemplate;
import com.mnotice.message.repository.FreemarkerTemplateRepository;
import freemarker.cache.TemplateLoader;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.time.LocalDateTime;

@Component("databaseTemplateLoader")
public class DbTemplateLoader implements TemplateLoader {

    @Resource
    private FreemarkerTemplateRepository templateRepository;

    @Override
    public Object findTemplateSource(String projectIdAndName) {
        if (projectIdAndName.contains(".")) return new FreemarkerTemplate();
        String[] s = projectIdAndName.split("_");
        return templateRepository.findByProjectIdAndName(s[0], s[1]);
    }

    @Override
    public long getLastModified(Object templateSource) {
        FreemarkerTemplate template = (FreemarkerTemplate) templateSource;
        LocalDateTime updateAt = template.getUpdateAt();
        return updateAt == null ? 0 : updateAt.getSecond();
    }

    @Override
    public Reader getReader(Object templateSource, String encoding) throws IOException {
        String content = ((FreemarkerTemplate) templateSource).getContent();
        return new StringReader(content == null ? "" : content);
    }

    @Override
    public void closeTemplateSource(Object templateSource) throws IOException {
    }
}